﻿namespace StateTheater
{
	using System;
	using System.Reflection;
	using System.Text.RegularExpressions;
	using Castle.MonoRail.Framework;

	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public class DecodeBinderAttribute : Attribute, IParameterBinder
	{
		#region IParameterBinder Members

		public object Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
		{
			var token = context.Request[parameterInfo.Name];
			return Util.Decode(token);
		}

		const string nonBase64chars = @"^[^A-Za-z0-9+~]$";
		static readonly Regex encodedChars = new Regex(nonBase64chars);
		
		public int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
		{
			var token = context.Request[parameterInfo.Name];
			if (encodedChars.IsMatch(token))
				return 0;
			return 10;
		}

		#endregion
	}
}
